package com.flycms.modules.user.util;

import io.jsonwebtoken.*;
import com.flycms.common.constant.Constants;
import com.flycms.common.utils.StrUtils;
import com.flycms.framework.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class JwtTokenUtils {
    @Autowired
    private RedisCache redisCache;

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);

    private static final int EXPIRE_DATE = 30 * 60 * 1000; //过期时间30分钟

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    // 生成密钥
    private static final String SECRET = "WH#$%(!)(#*!()!KL<55$6><MQLMNQNQJQK EiLCJuYW1lIjoif>?N<:{LWPW";
    // Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045～RFC2049，上面有MIME的详细规范。
    // signWith中，如果传递字符串，需要传递base64编码的字符串

    /**
     * 生成的密钥
     */
    private static final Key SIGN_KEY = generalSecretKey(SignatureAlgorithm.HS256, SECRET);

    /**
     * 生成key，用于生成token
     *
     * @param signatureAlgorithm 指定加密算法
     * @param secretKey          自定义秘钥，仅仅后台知道
     * @return Key
     */
    public static Key generalSecretKey(SignatureAlgorithm signatureAlgorithm, String secretKey) {
        // 在Java 8在java.util包下面实现了BASE64编解码API，API简单易懂
        byte[] base64EncodedSecretKey = null;
        try {
            base64EncodedSecretKey = Base64.getEncoder().encode(secretKey.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 这样也是可以的 Key key = MacProvider.generateKey()
        if (base64EncodedSecretKey == null) {
            throw new IllegalArgumentException();
        }
        return new SecretKeySpec(base64EncodedSecretKey, signatureAlgorithm.getJcaName());
    }

    /**
     * 创建token
     *
     * @param userId 用户id
     * @return
     */
    public String generateToken(Long userId){
        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY,null == userId ? null : userId.toString());
       //设置头部信息
        Map<String,Object> header = new HashMap<>();
        header.put("typ","JWT");
        header.put("alg","HS256");
        return Jwts.builder()
                .setHeader(header)
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_DATE))
                .signWith(SIGN_KEY,SignatureAlgorithm.HS256)    // 设置安全密钥（生成签名所需的密钥和算法）
                .compact();
    }

    /**
     * 验证token是否有效
     *
     * @param token
     * @return
     */
    public boolean tokenValidate(String token){
        try {
            if(verify(token) != null &&  isExpired(token)) {
                return true;
            }
        }catch (ExpiredJwtException e){
            logger.error(e.getMessage());
            return false;
        } catch (JwtException e) {
            logger.error(e.getMessage());
            return false;
        } catch (Exception e){
            logger.error(e.getMessage());
            return false;
        }
        return false;
    }

    /**
     * 验证token是否有效
     *
     * @param token
     * @return
     */
    public Boolean verify(String token){
        try {
            Jwts.parserBuilder().setSigningKey(SIGN_KEY).build().parseClaimsJws(token);
            return true;
        }catch (ExpiredJwtException e){
            logger.error(e.getMessage());
            return false;
        } catch (JwtException e) {
            logger.error(e.getMessage());
            return false;
        } catch (Exception e){
            logger.error(e.getMessage());
            return false;
        }
    }

    /**
     * 检查token是否过期
     *
     * @param token
     * @return
     */
    public boolean isExpired(String token){
        try{
            Claims claims = getClaimsToken(token);
            return claims.getExpiration().after(new Date(System.currentTimeMillis()));
        }catch (ExpiredJwtException e){
            logger.error(e.getMessage());
            return false;
        }
    }

    /**
     * 检查token内是否包含用户id
     *
     * @param token
     * @return
     */
    public Long getUserToken(String token){
        try{
            if (StrUtils.isNotEmpty(token)){
                Claims claims = getClaimsToken(token);
                if(claims != null){
                    String userId = (String) claims.get(Constants.LOGIN_USER_KEY);
                    System.out.println("======userId======="+userId);
                    if(StrUtils.isNotEmpty(userId)){
                        String tokenCache = redisCache.getCacheObject(userId).toString();
                        Claims parseJwt=getClaimsToken(tokenCache);
                        System.out.println("======Long.parseLong(parseJwt.get(Constants.LOGIN_USER_KEY).toString())======="+Long.parseLong(parseJwt.get(Constants.LOGIN_USER_KEY).toString()));
                        return Long.parseLong(parseJwt.get(Constants.LOGIN_USER_KEY).toString());
                    }
                }
            }
        }catch (ExpiredJwtException e){
            logger.error(e.getMessage());
            return null;
        }
        return null;
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginAdmin(String token)
    {
        if (StrUtils.isNotEmpty(token))
        {
            String userKey = getUserToken(token).toString();
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 获取token内参数
     *
     * @param token
     * @return
     */
    public Claims getClaimsToken(String token) {
        if(verify(token)){
            Claims claims;
            try {
                claims = Jwts.parserBuilder().setSigningKey(SIGN_KEY).build().parseClaimsJws(token).getBody();
                return claims;
            }catch (ExpiredJwtException e){
                logger.error(e.getMessage());
                return null;
            } catch (JwtException e) {
                logger.error(e.getMessage());
                return null;
            } catch (Exception e){
                logger.error(e.getMessage());
                return null;
            }
        }
        return null;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param token 令牌
     * @return 令牌
     */
    public void verifyToken(String token)
    {
        Claims parseJwt = getClaimsToken(token);
        Date d2 = parseJwt.getExpiration();
        long expireTime = d2.getTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(Long.parseLong(parseJwt.get(Constants.LOGIN_USER_KEY).toString()));
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param userId 登录信息
     */
    public void refreshToken(Long userId)
    {
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(String.valueOf(userId));
        String newToken = generateToken(userId);
        redisCache.setCacheObject(userKey, newToken, EXPIRE_DATE, TimeUnit.MINUTES);
    }

    private String getTokenKey(String uuid)
    {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/*    public static void main(String[] args) throws Exception{
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("username", "zss");
        String jwt = generateToken(1l);
        System.out.println(jwt);
        Claims parseJwt = getClaimsToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbl91c2VyX2tleSI6IjEiLCJpYXQiOjE1OTEyNTkyMjUsImV4cCI6MTU5MTI2MTAyNX0.YKPhA7Y5LbIRP_hio9T2yuocuXwt94EPW8zGPMzsNvc");
        Date d1 = parseJwt.getIssuedAt();
        Date d2 = parseJwt.getExpiration();
        System.out.println("令牌签发时间：" + sdf.format(d1));
        System.out.println("令牌过期时间：" + sdf.format(d2));
        System.out.println("userId：" + parseJwt.get(Constants.LOGIN_USER_KEY));
        System.out.println("verify：" + verify(jwt));
        System.out.println("isExpired：" + isExpired(jwt));
        System.out.println("tokenValidate：" + tokenValidate(jwt));
        System.out.println("userId：" + String.valueOf(getUserToken(jwt)));

        long expireTime = d2.getTime();
        long currentTime = System.currentTimeMillis();
        System.out.println(expireTime - currentTime);
        boolean sss = expireTime - currentTime <= MILLIS_MINUTE_TEN;
        System.out.println(sss+"----------"+MILLIS_MINUTE_TEN);
    }*/
}
